import { Component, OnInit, OnChanges } from '@angular/core';
import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import 'rxjs/add/operator/toPromise';
import { Router, ActivatedRoute } from '@angular/router';
import { AuthService } from '../../../core/service/auth/auth.service';
import { HttpClient } from '@angular/common/http';
import { differenceInCalendarDays } from 'date-fns';
import { DatePipe } from '@angular/common';

@Component({
	selector: 'app-prescriptions-folder',
	templateUrl: './prescriptions-folder.component.html',
	styleUrls: ['./prescriptions-folder.component.scss']
})
export class PrescriptionsFolderComponent implements OnInit {
	// 审方类型
	prescriptionType: number;
	// filter过滤属性
	prescriptions: any = '';
	patientName: any = '';
	administrativeOffice: any = '';
	doctor: any = '';
	status: any = '';
	illegalReason: any = '';
	// 当前操作是那一条
	currentIndex: number;
	// 当前页面页脚信息
	currentPage: number = 1;
	pages: number;
	total: number;
	targetPage: number = 1;
	// 单条操作信息
	itemOpearte: string;
	modelTextarea: string = '';
	showModels: boolean = false;
	patientList: any[] = [
	];
	// test开始时间
	searchParams: any = {
		start_date: this.getCurrentMonthFirst(),
		end_date: new Date()
	};
	constructor(private route: Router, private activatedRoute: ActivatedRoute, public auth: AuthService, private http: HttpClient, public datePipe: DatePipe) { }

	ngOnInit() {
		this.activatedRoute.queryParams.subscribe(queryParams => {
			// 判断是事前还是事后的审方
			const message = queryParams.infoMessage;
			if (message === 'advance') {
				this.prescriptionType = 1;
			} else if (message === 'after') {
				this.prescriptionType = 2;
			}
			this.obtainPatientList();
			// let title = queryParams.title;
		});
	}
	/**
	 * 这是获取当月第一天的事件
	 */
	getCurrentMonthFirst() {
        const date = new Date();
        date.setDate(1);
		// let month = NuparseInt(date.getMonth() + 1);
		let month: any = Number.parseInt((date.getMonth() + 1).toString());
        let day: any = date.getDate();
        if (month < 10) {
            month = '0' + month;
        }
        if (day < 10) {
            day = '0' + day;
        }
        return date.getFullYear() + '-' + month + '-' + day + ' ' + '00:00:00';
	}
	disabledDate = (current: Date): boolean => {
		// Can not select days before today and today
		return differenceInCalendarDays(current, this.searchParams['start_date']) < 0 || differenceInCalendarDays(current, this.searchParams['start_date']) === 0;
	  }
	/**
	 * 这是批量处理patientList数组，添加或者删除checked属性
	 */
	handlePatientList(arr, operate) {
		if (operate === 'add') {
			arr.forEach(function (item) {
				item.checked = false;
			});
		} else {
			arr.forEach(function (item) {
				if (item.hasOwnProperty('checked')) {
					delete item.checked;
				}
			});
		}
		return arr;
	}
	/**
	 * 这是通过form表单输入检索获取list集合,无论是进页面还是输入检索时候获取
	 */
	obtainPatientList() {
		const list = this.handlePatientList(this.patientList, 'delete');
		// 如果没有就不用传，object属性为空
		const params: any = {
			// 这里填写用户信息及list集合，还需要当前页面的页脚等信息
			recipe_type: this.prescriptionType,
			recipe_id: this.prescriptions,
			patient_name: this.patientName,
			department:  this.administrativeOffice,
			doctor_name:  this.doctor,
			recipe_status: this.status,
			illegal_reason: this.illegalReason,
			order_by: '-create_time',
			current_page: this.currentPage,
			per_page: 20,
		};
		if (this.prescriptionType === 2) {
				// 开始时间和结束时间
				params.create_time_gte =  this.datePipe.transform(this.searchParams.start_date, 'yyyy-MM-dd HH:mm:ss');
				params.create_time_lt =    this.datePipe.transform(this.searchParams.end_date, 'yyyy-MM-dd HH:mm:ss');
		}
		// 删除value不存在的属性
		for (const i in params) {
			if (!params[i] || params[i] === '') {
				delete params[i];
			}
		}
		console.log('this.params_' + params);
		this.http.get(window.API_ROOT + 'api/recipes', {params: params}).subscribe((res: any) => {
			// console.log('this.status_' + this.status);
			this.patientList = res.data.results;
			this.handlePatientList(this.patientList, 'add');
			this.pages = res.data.total_page;
			this.total = res.data.total_num;
		});
	}
	/**
	 * 这是进行批量操作
	 */
	batchOperate(operate) {
		const patientList = this.haveSelected();
		if (patientList.length === 0) {
			return;
		}
		console.log('patientList_' + patientList);
	}
	/**
	 * 获取已经选中的数据
	 */
	haveSelected() {
		const haveSelected = [];
		this.patientList.forEach(function (item) {
			if (item.checked) {
				haveSelected.push(item);
			}
		});
		return haveSelected;
	}
	/**
	 * 跳转页面
	 */
	goToPage(event) {
		const info = event.target.innerText;
		if (info === '上一页' && this.currentPage !== 1) {
			this.currentPage--;
		} else if (info === '下一页' && this.currentPage !== this.pages) {
			this.currentPage++;
		} else if (info === 'Goto') {
			this.targetPage > this.pages ? this.targetPage = this.pages : this.targetPage = this.targetPage;
			this.currentPage = this.targetPage;
		} else if (info === '首页') {
			this.currentPage = 1;
		} else if (info === '尾页') {
			this.currentPage = this.pages;
		} else {
			return;
		}
		// 这边到时候要加上一个获取list集合的请求
		console.log('info_' + this.currentPage);
		this.obtainPatientList();
	}
	/**
	 * 通过，打回弹出窗
	 */
	itemOperation(index, event) {
		this.currentIndex = index;
		this.itemOpearte = event.target.innerText;
		console.log('this.currentIndex_', this.currentIndex);

		const operate = event.target.innerText;
		if (operate === '通过' || operate === '打回') {
			this.modelTextarea = '';
			this.showModels = true;
		} else if (operate === '查看') {
			window.open('#/main/prescriptions/prescriptions-details' + '?infoMessage=' + this.patientList[this.currentIndex]['处方id']);
		}
	}
	/**
	 * 刷新,获取最新数据
	 */
	refesh() {
		this.currentPage = 1;
		this.obtainPatientList();
	}
	/**
	 * 弹出框阻止冒泡
	 */
	stopPropagation(event) {
		event.stopPropagation();
	}
	/**
	 * 关闭弹出框
	 */
	closeModel() {
		this.showModels = false;
	}
	/**
	 * 弹出框确认
	 */
	confirmModel() {
		this.closeModel();
		const params = [{
			'处方id': this.patientList[this.currentIndex]['处方id'] ,
			'操作类型': this.itemOpearte ,
			'人工审核': this.itemOpearte === '通过' ? 1 : 2,
			'备注': this.modelTextarea
		}];
		this.http.post(window.API_ROOT + 'api/recipes', params).subscribe((res) => {
			console.log(res);
			this.patientList[this.currentIndex]['备注'] = this.modelTextarea;
			this.patientList[this.currentIndex]['审核状态'] =   (this.itemOpearte === '通过' ? 1 : 2) ;
			this.refesh();
		});
	}
	/**
	 * 查看操作记录
	 */
	operatingRecord() {
		console.log(this.route);
		window.open('#/main/prescriptions/operation-record');
	}
	/**
	 * @description 打开备注详情
	 */
	openRemarks(index) {
		window.open('#/main/prescriptions/prescriptions-remarks' + '?infoMessage=' + this.patientList[index]['处方id']);
	}
}
